<template>
	<view class="container" :style="activityJson?.wrapper?.style">
		<!-- <view class="join-card" @click="toUrl('/pageUser/myActivity/index')">
			<view>参与</view>
			<view>记录</view>
		</view>
		<view class="join-card" @click="toUrl('/pageUser/equityReward/index')">
			<view>我的</view>
			<view>卡包</view>
		</view> -->
		<view class="wheel-container" :style="activityJson?.content?.style">
			<view class="inner">
				<wheel size="100%" ref="wheelRef" :prizeList="prizeList" :pointerStyle="activityJson?.btn?.style" :pointerText="activityJson?.btn?.text" @click="onClick"
					@done="onDone">
					<template #prize={item}>
						<view class="prize">
							<template v-if="item.awardType === 0"> <!-- 卡券 -->
								<view class="name">{{ item.awardName }}</view>
								<view class="coupon">{{ item.awardPrice / 100 }}</view>
							</template>
							<template v-if="item.awardType === 3"> <!-- 福分 -->
								<view class="name">{{ item.awardName }}</view>
								<view class="score">{{ item.awardPrice }}</view>
							</template>
							<template v-if="item.awardType === 'self'"> <!-- 前端自定义 -->
								<view class="name">{{ item.awardName }}</view>
								<view class="score" :style="{ 'background-image': `url(${item.img})` }"></view>
							</template>
						</view>
					</template>
				</wheel>
			</view>
		</view>
		<!-- 抽奖次数 -->
		<view class="draw-num" :style="activityJson?.times?.style">{{ activityJson?.times?.text ? activityJson.times.text.replace(/%s/,drawTimes) : `您还有${drawTimes}次抽奖机会` }}</view>
		<!-- 玩法介绍 -->
		<view class="rules" :style="activityJson?.rule?.style">
			<!-- <view v-for="item in activityDetail.remark">{{ item }}</view> -->
			<text>{{ activityDetail.remark?.replace(/\\n/g, "\n") }}</text>
		</view>
		<!-- 授权登录弹窗 -->
		<gzLoginPopup ref="gzLoginPopupRef" v-model:isLogin="vdata.isLogin" @isLoginCallback="isLoginCallback"></gzLoginPopup>
	</view>
</template>

<script setup>
	import wheel from './components/wheel.vue'
	import { $activityTakePartIn, $getAwardList, $getAwardTimes } from '@/http/apiManager.js'
	import storageManage from '@/util/storageManage.js'
	import { ref, getCurrentInstance, reactive } from 'vue'
	import { onLoad, onShow, onShareAppMessage } from '@dcloudio/uni-app'

	const { $infoBox } = getCurrentInstance().appContext.config.globalProperties
	const isClick = ref(false) //防止连续点击
	const activityDetail = ref({}) // 活动详情

	const drawTimes = ref(0) // 活动详情
	const activityId = ref() // 活动详情
	const activityChannelId = ref() // 活动渠道码
	const prizeList = ref([]) // 活动详情
	// const hasMchNo = ref(undefined)	// 活动详情
	const hasMchNo = ref({}) // 活动详情
	const wheelRef = ref()
	const gzLoginPopupRef = ref()
	
	// 数据源
	const vdata = reactive({
		isLogin: false,	// 用户是否登录
	})
	
	// 默认活动内容
	const activityJson = ref({
		"wrapper":{
			"style":{
				"background":"url('https://jdyd-marketing-public.oss-cn-hangzhou.aliyuncs.com/yx/874bd1db-a2f0-47b1-af01-3e3863c78976.png') no-repeat left top / 100% 1288rpx, #ff6932"
			}
		},
		"content":{
			"style":{
				"margin-top":"364rpx",
				"width":"660rpx",
				"height":"660rpx",
				"background":"url('https://jdyd-marketing-public.oss-cn-hangzhou.aliyuncs.com/yx/963982f3-e22b-4d02-8b6b-942fec450e31.png') no-repeat left top / 100% 100%"
			}
		},
		"btn":{
			"text":"",
			"style":{
				"width":"410rpx",
				"height":"440rpx",
				"background":"url('https://jdyd-marketing-public.oss-cn-hangzhou.aliyuncs.com/yx/0180478d-80d0-428a-950d-6c4e13b90ab2.png') no-repeat left top / 100% 100%"
			}
		},
		"rule":{
			"style":{
				"margin-top":"154rpx",
				"color":"#333",
				"background":"#fffcf3"
			}
		},
		"times":{
			"text":"您还有%s次抽奖机会",
			"style":{
				"margin-top":"74rpx",
				"color":"#fff"
			}
		}
	})

	onLoad(async (params) => {
		vdata.isLogin = storageManage.isLogin()
		activityId.value = params.activityId
		// 判断用户是否登录过
		if (!vdata.isLogin) {
			uni.showModal({
				title: '提示',
				content: '请先进行登录注册，再进行参与！',
				success({ cancel }) {
					if (cancel) {
						$infoBox.toast('登录失败，无法正常参与活动！')
					} else {
						gzLoginPopupRef.value.open() // 打开授权弹框
					}
				}
			})
		}
		// 请求活动详情
		activityDetail.value = JSON.parse(decodeURIComponent(params.activityDetail))
		// 活动渠道码
		activityChannelId.value = params.activityChannelId
		// 活动动态参数
		activityJson.value = JSON.parse(activityDetail.value.activityJson || '{}')
		// 标题更改为活动名称
		uni.setNavigationBarTitle({
			title: activityDetail.value.activityName || '幸运大转盘'
		})
		// 请求奖品列表
		getAwardList(params.activityId)
	})

	onShow(async () => {
		vdata.isLogin = storageManage.isLogin()
		// 登录才拉取抽奖次数
		if(vdata.isLogin){
			await getAwardTimes(activityId.value)
		}
	})
	
	/**
	 * 登录回调 登录成功后 请求抽奖次数
	 */
	function isLoginCallback(){
		if(vdata.isLogin){
			getAwardTimes(activityId.value)
		}
	}


	function onDone({ prize, type }) {
		if (type === 0) {
			uni.showModal({
				title: prize.id == 'thanks' ? '很遗憾' : '恭喜您',
				content: (prize.id !== 'thanks' ? `获得` : '') + prize.awardName,
				success({
					cancel
				}) {
					if (cancel) return
					if (prize.awardType === 0) { // 卡券
						toUrl('/pageUser/myCoupon/index?couponState=0&tabCurrent=1')
					} else if (prize.awardType === 3) { // 福分
						toUrl('/pageUser/scoreRecords/index')
					}
				}
			})
		} else if (type === 1) {
			uni.showModal({
				title: '很遗憾',
				content: '谢谢参与'
			})
		} else { // 参与失败 什么都不展示

		}
		isClick.value = false
	}
	/**
	 * 拉取奖品列表
	 * @param {String} activityId 活动ID
	 */
	function getAwardList(activityId) {
		$getAwardList({
			activityId
		}).then(({
			bizData
		}) => {
			let tempObj = {
				awardType: 'self', // 
				awardAliasName: '安慰奖',
				awardLevel: '4',
				id: 'anweijiang',
				awardName: '谢谢参与',
				price: '',
				img: 'https://jdyd-marketing-public.oss-cn-hangzhou.aliyuncs.com/yx/c4fa14fd-6e36-454c-83a4-8e2dcd6ec435.png',
			}
			bizData.unshift(tempObj)
			Object.assign(prizeList.value, bizData)
		})
	}
	/**
	 * 拉取抽奖次数
	 * @param {String} activityId 活动ID
	 */
	async function getAwardTimes(activityId) {
		try {
			const result = await $getAwardTimes(activityId, activityDetail.value.activityTemplateNo)
			drawTimes.value = result
			hasMchNo.value = undefined
		} catch (e) {
			hasMchNo.value = e
		}
	}

	function onClick() {
		if (!vdata.isLogin) {
			gzLoginPopupRef.value.open() // 打开授权弹框
			return
		}
		if (isClick.value) return
		isClick.value = true
		// 奖品的索引
		// 判断用户是否绑定商户
		if (hasMchNo.value === 'noMchNo') { // 代表是商家版活动 并且当前用户还未绑定商户号 不允许参与活动
			uni.showModal({
				title: '参与失败',
				content: '当前用户未绑定商户身份，请绑定商户身份',
				success({
					cancel
				}) {
					if (cancel) return
					uni.navigateTo({
						url: '/pageUser/bindMch/index'
					})
				}
			})
			isClick.value = false
			return
		}
		/**
		 * 是否有参与次数再次判断 拦截
		 */

		if (drawTimes.value <= 0) {
			$infoBox.toast('您的抽奖机会已用尽')
			isClick.value = false
			return
		}
		uni.showLoading({
			title: '加载中'
		})
		$activityTakePartIn({
			activityId: activityId.value,
			activityTemplateNo: activityDetail.value.activityTemplateNo,
			activityChannelId: activityChannelId.value
		}).then(({ code, bizData }) => {
			uni.hideLoading()
			// 减少抽奖次数
			if (bizData.awardName) { // 表示中奖
				try {
					prizeList.value.forEach((item, index) => {
						if (item.awardId === bizData.awardId) {
							wheelRef.value.run(index)
							throw new Error('break')
						}
					})
				} catch (e) {
					//TODO handle the exception
				}
			} else { // 未中奖
				wheelRef.value.run(0, 1)
			}
			drawTimes.value -= 1 // 减少抽奖次数
		}).catch(() => {
			wheelRef.value.run(0, 2)
		})
	}
	/**
	 * 跳转页面
	 * @param {Object} url 跳转页面地址
	 */
	function toUrl(url) {
		uni.navigateTo({
			url,
		})
	}
	/**
	 * 页面分享
	 */
	// onShareAppMessage((option) => {
	// 	return {
	// 		path: `/pages/welcome/index?share=${JSON.stringify({ activityId: activityId.value, inviterId: storageManage.fansId() })}`, // 分享的页面路径
	// 	};
	// })
</script>

<style lang="less">
	.container {
		width: 100%;
		box-sizing: border-box;
		position: relative;
		min-height: 100vh;
		overflow: hidden;
		background: url('https://jdyd-marketing-public.oss-cn-hangzhou.aliyuncs.com/yx/874bd1db-a2f0-47b1-af01-3e3863c78976.png') no-repeat left top / 100% 1288rpx, #ff6932;

		.join-card {
			position: absolute;
			right: 0;
			top: 100rpx;
			background-color: #FF7B55;
			border-radius: 40rpx 0 0 40rpx;
			color: #fff;
			font-size: 20rpx;
			padding: 10rpx 20rpx 10rpx 30rpx;

			&:nth-of-type(2) {
				top: 210rpx;
			}
		}

		.wheel-container {
			margin-top: 364rpx;
			width: 660rpx;
			height: 660rpx;
			margin-left: calc(50% - 330rpx);
			background: url('https://jdyd-marketing-public.oss-cn-hangzhou.aliyuncs.com/yx/963982f3-e22b-4d02-8b6b-942fec450e31.png') no-repeat left top / 100% 100%;
			overflow: hidden;

			.inner {
				width: 88.5%;
				height: 88.5%;
				background-color: #ffffff;
				border-radius: 50%;
				margin-left: calc(6%);
				margin-top: calc(6%);
			}
		}

		.draw-num {
			font-size: 28rpx;
			width: 100%;
			text-align: center;
			
			margin-top: 74rpx;
			color: #fff;
		}

		.rules {
			margin: 154rpx 36rpx 36rpx;
			padding: 24rpx;
			font-size: 24rpx;
			border-radius: 24rpx;
			display: flex;
			flex-direction: column;
			gap: 12rpx;
			color: #333;
			background: #fffcf3;
		}

	}


	// 插槽中卡券和福分样式
	.prize {
		display: flex;
		flex-direction: column;
		align-items: center;
		gap: 10rpx;
		margin-top: 20rpx;

		.name {
			font-size: 28rpx;
			color: #8F2C0C;
		}

		.coupon {
			width: 134rpx;
			height: 77rpx;
			background-image: url('https://jdyd-marketing-public.oss-cn-hangzhou.aliyuncs.com/yx/58e97b13-989e-4e7a-bcf4-cf07ad309399.png');
			background-size: 100% 100%;
			background-repeat: no-repeat;
			background-position: 0 0;
			color: #fff;
			font-weight: bold;
			font-size: 32rpx;
			padding: 10rpx 20rpx;
			box-sizing: border-box;
			position: relative;
			display: flex;
			justify-content: space-between;
			align-items: center;

			&::after {
				content: '消费券';
				display: block;
				color: #fff;
				font-size: 15rpx;
				font-weight: normal;
				writing-mode: vertical-rl;
			}
		}

		.score {
			width: 90rpx;
			height: 90rpx;
			background-image: url('https://jdyd-marketing-public.oss-cn-hangzhou.aliyuncs.com/yx/5e2c4637-fbb0-4815-9464-12c39087102c.png');
			background-size: 100% 100%;
			background-repeat: no-repeat;
			display: flex;
			align-items: center;
			justify-content: center;
			color: #8F2C0C;
		}
	}
</style>